package zj.com.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import zj.com.adapter.FragmentTabAdapter;
import zj.com.adapter.FragmentTabAdapter.OnRgsExtraCheckedChangedListener;
import zj.com.app.ZjApplication;
import zj.com.crash.UncaughtExceptionHandler;
import zj.com.fragments.GrzxFragment;
import zj.com.fragments.XcjcFragment;
import zj.com.fragments.XcjkFragment;
import zj.com.fragments.ZljkFragment;
import zj.com.model.AppVersion;
import zj.com.model.Zy;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.service.VersionService;
import zj.com.util.CommonUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;
import android.app.AlertDialog.Builder;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by xi on 16/5/31.
 */
public class MainTabActivity extends FragmentActivity {
    private RadioGroup rgs;
    public List<Fragment> fragments = new ArrayList<Fragment>();
    public static int loading_process = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_tab);
        ZjApplication.getInstance().addActivity(this);

        fragments.add(new XcjcFragment());
        fragments.add(new ZljkFragment());
        fragments.add(new XcjkFragment());
        fragments.add(new GrzxFragment());






        rgs = (RadioGroup) findViewById(R.id.tabs_rg);

        FragmentTabAdapter tabAdapter = new FragmentTabAdapter(this, fragments, R.id.tab_content, rgs);
        tabAdapter.setOnRgsExtraCheckedChangedListener(new OnRgsExtraCheckedChangedListener() {
            @Override
            public void OnRgsExtraCheckedChanged(RadioGroup radioGroup, int checkedId, int index) {
                System.out.println("Extra---- " + index + " checked!!! ");
            }
        });

        check();
    }


    public void check(){

        NetManager.getInstance(this).checkVersion(new OnResponseListener<AppVersion>() {
            @Override
            public void onComplete(boolean isOK, AppVersion result, int errorCode, String errorMsg) {

                if(isOK){
                    version(result);
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

            }
        });
    }

    public void version(final AppVersion version){


        int versionCode = CommonUtil.getVerCode(this);
        LogUtils.getInstance().error("===version===="+version.getCode()+"   versionCode==="+versionCode);
        if(version != null && version.getCode() > versionCode){

            Dialog dialog = new AlertDialog.Builder(
                    MainTabActivity.this)
                    .setTitle("新版本更新内容")
                    .setMessage(version.getDesc())
                    .setPositiveButton("马上更新",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    beginning(version);
                                    dialog.dismiss();
                                }
                            })
                    .setNegativeButton("以后再说",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    dialog.dismiss();
                                }
                            }).create();
            dialog.show();

        }
    }

    public ProgressBar pb;
    public TextView tv;
    public void beginning(final AppVersion version){
        LinearLayout ll = (LinearLayout) LayoutInflater.from(MainTabActivity.this).inflate(
                R.layout.layout_loadapk, null);
        pb = (ProgressBar) ll.findViewById(R.id.down_pb);
        tv = (TextView) ll.findViewById(R.id.tv);
        Builder builder = new Builder(MainTabActivity.this);
        builder.setView(ll);builder.setTitle("版本更新进度提示");
        builder.setNegativeButton("后台下载",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent(MainTabActivity.this, VersionService.class);
                        startService(intent);
                        dialog.dismiss();
                    }
                });

        builder.show();
        new Thread() {
            public void run() {
                loadFile(version.getAppUrl());
            }
        }.start();
    }

    public void loadFile(String url) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            float length = entity.getContentLength();

            InputStream is = entity.getContent();
            FileOutputStream fileOutputStream = null;
            if (is != null) {
                File file = new File(Environment.getExternalStorageDirectory(),
                        "NightMan.apk");
                fileOutputStream = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int ch = -1;
                float count = 0;
                while ((ch = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, ch);
                    count += ch;
                    sendMsg(1,(int) (count*100/length));
                }
            }
            sendMsg(2,0);
            fileOutputStream.flush();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (Exception e) {
            sendMsg(-1,0);
        }
    }
    private void sendMsg(int flag,int c) {
        Message msg = new Message();
        msg.what = flag;msg.arg1=c;
        handler.sendMessage(msg);
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 1:
                        pb.setProgress(msg.arg1);
                        loading_process = msg.arg1;
                        tv.setText("已为您加载了：" + loading_process + "%");
                        break;
                    case 2:
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(Environment
                                        .getExternalStorageDirectory(), "NightMan.apk")),
                                "application/vnd.android.package-archive");
                        startActivity(intent);
                        break;
                    case -1:
                        String error = msg.getData().getString("error");
                        Toast.makeText(MainTabActivity.this, error, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

}
